using System;
using System.IO;

namespace Org.JSON
{
	public sealed class String : Value
	{
		public String (string value)
		{
			if(value == null) {
				throw new ArgumentNullException("Value of json string can't be null. Use Org.JSON.Null instead");
			}

			this.value = value;
		}

		private string value;

		public string Value { get { return this.value; }}

		public override void Serialize(TextWriter stream)
		{
			stream.Write('"');

			foreach(var chr in this.Value)
			{
				var code = (ushort) chr;
				if(chr == '\\')
				{
					stream.Write("\\\\");
				}
				else if(chr == '\"')
				{
					stream.Write("\\\"");
				}
				else if(chr == '\n')
				{
					stream.Write("\\n");
				}
				else if(chr == '\r')
				{
					stream.Write("\\r");
				}
				else if(chr == '\f')
				{
					stream.Write("\\f");
				}
				else if(chr == '\b')
				{
					stream.Write("\\b");
				}
				else if(chr == '\t')
				{
					stream.Write("\\t");
				}
				else if(code <= 0x1F || code >= 0x80 && code <= 0x9F || code == 0x7F)
				{
					stream.Write("\\u");
					stream.Write(string.Format("{0:x4}", code));
				}
				else
				{
					stream.Write(chr);
				}
			}

			stream.Write('"');
		}

		public static String From(string json)
		{
			return Org.JSON.Value.From(json) as String;
		}
	}
}

